<?php
/**
 * Created by PhpStorm.
 * User: zhangbing
 * Date: 2017/5/24 0024
 * Time: 11:58
 */
namespace app\service;
use app\api\controller\Base;
use app\models\Models;

class SmsMiaodi extends Base {
    /**
     * 发送短信
     * @param array $data
     * @return bool
     */
    public function sendCode($data = ['action'=>'','mobile'=>'']){
        // 条件验证
        self::errorMsg($data);
        // 组合传递参数
        $message = ['register'=>'手机注册验证', 'login'=>'立即登录', 'forgetPassword'=>'忘记密码', 'changePassword'=>'修改密码',];
        $param['code']  = rand(1000,9999);//随机生成验证码
        $param['url']   = 'https://api.miaodiyun.com/20150822/industrySMS/sendSMS';
        $param['sid']   = '567adcdf31ed40589476839eb91b7108';
        $param['token'] = '27ffc037af18488b904c6ebdd5fdccd1';
        $param['time']  = date('YmdHis');
        $param['sig']   = md5($param['sid'].$param['token'].$param['time']);
        $param['text']  = "【国诚投顾】验证码:{$param['code']}, 15分钟有效, {$message[$data['action']]}";
        $param['to']    = $data['mobile'];

        // 发送短信请求
        $result = self::smsRequest($param);
        if($result['respCode'] == '00000'){
            // 将验证码存储于redis中
            $redis = new Redis();
            $redis->set($data['mobile'].$data['action'],60*15,$param['code']);
            return true;
        }
        return false;
    }

    /**
     * 发送短信请求
     * @param $param
     * @return bool
     */
    protected function smsRequest($param){
        $ch = curl_init();
        /* 设置验证方式 */
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded','charset=utf-8'));
        /* 设置返回结果为流 */
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        /* 设置超时时间*/
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        /* 设置通信方式 */
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        // 发送短信
        $data = array('accountSid'=>$param['sid'],'smsContent'=>$param['text'],'to'=>$param['to'],'timestamp'=>$param['time'],'sig'=>$param['sig']);
        curl_setopt ($ch, CURLOPT_URL, $param['url']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        $json_data = curl_exec($ch);
        //将数据转换成数组
        return json_decode($json_data,true);
    }

    /**
     * @param array $data
     * 验证数据
     */
    protected function errorMsg($data = []){
        if(empty($data['action']) || empty($data['mobile'])){
            throw new \LogicException('参数错误',1000);
        }
        $user = new Models('user');
        $info = $user->_find(['username'=>$data['mobile']]);
        if($data['action'] == 'register' && $info){
            throw  new \LogicException('您的帐号已存在',1001);
        }
        if($data['action'] == 'forgetPassword' && !$info){
            throw  new \LogicException('该用户尚未注册',1002);
        }
    }
}